package com.accesshollywood.grfxOrdering.panels;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.TransferHandler;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import com.accesshollywood.grfxOrdering.basics.Colors;
import com.accesshollywood.grfxOrdering.basics.NamedList;
import com.accesshollywood.grfxOrdering.basics.Users;
import com.accesshollywood.grfxOrdering.orderTreeSpecial.models.AbstractButtonPlusModel;
import com.accesshollywood.grfxOrdering.orderTreeSpecial.models.ButtonAndListModel;
import com.accesshollywood.grfxOrdering.panels.DragNDropPanel.DROP;
import com.accesshollywood.indexables.GrfxOrder;
import com.accesshollywood.indexables.items.GrfxItem;
import com.accesshollywood.notifications.Notify;

public class ButtonListPanel extends JPanel {
	/*
//	public enum DROP {
//		STILLS,
//		FOOTAGE
//	}

	public GrfxOrder		grfxOrder;
	JComponent				parent;
	ButtonAndListModel		buttonAndListModel;
	// JList list;
	JTable	table;
	JCheckBox				chckbxSecret;		// only shows up if specific rights
												// are
												// available to user. Helps with
												// selecting things for editing or
												// removal.
	public DROP				drop;

	public ButtonListPanel(GrfxOrder model, JComponent parent, boolean useApproval) {
		super();
		this.grfxOrder = model;
		this.parent = parent;
		setBorder(new TitledBorder(new EtchedBorder(), ""));
	}

	public void setBGOnApproval(boolean useApproval) {
		if (useApproval && buttonAndListModel != null && !buttonAndListModel.approved) {
			setBackground(Colors.getColor(Colors.NOT_READY));
		} else {
			setBackground(Colors.getColor(Colors.DEFAULT_EVEN));
		}
	}

	public void createV(String label, NamedList listing, ArrayList<AbstractButtonPlusModel> allButtons) {
		buttonAndListModel = new ButtonAndListModel(label);

		setAlignmentX(Component.LEFT_ALIGNMENT);
		setAlignmentY(Component.TOP_ALIGNMENT);
		setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

		buttonAndListModel.setAlignmentX(Component.LEFT_ALIGNMENT);
		buttonAndListModel.listing = listing;

		if (label.equals("Copy")) {
			buttonAndListModel.listing.type = NamedList.TYPE.TEXT;
			//table = new EditableOneColumnTable("text","text","idText");
		} else if (label.equals("Open Stills")) {
			buttonAndListModel.listing.type = NamedList.TYPE.STILLS;
			//table = new EditableOneColumnTable("still","description","idStill");
		} else if (label.equals("Open Fotoage")) {
			buttonAndListModel.listing.type = NamedList.TYPE.FOOTAGE;
			//table = new EditableOneColumnTable("footage","description","idFootage");
		} else{
			table = new JTable();
		}
		
		 * list = new JList();
		 * list.setAlignmentX(Component.LEFT_ALIGNMENT);
		 * list.setModel(listing.toListModel());
		 * //list.setMaximumSize(new Dimension(475, 50));
		 * list.getSelectionModel().addListSelectionListener(new
		 * MyListSelectionListener());
		 

		GrfxOrder currOrder = grfxOrder;

		table.setAlignmentX(Component.LEFT_ALIGNMENT);
		if (currOrder != null) {
			table.setModel(listing.toTableModel(currOrder.getAssignedUsers()));
		} else {
			table.setModel(listing.toTableModel(null));
		}
		table.setTableHeader(null);
		table.getSelectionModel().addListSelectionListener(new MyListSelectionListener());
		table.getModel().addTableModelListener(new TableEditListener());
		table.setFillsViewportHeight(true);
		table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
		table.setShowGrid(false);
		table.setShowHorizontalLines(true);
		table.setShowVerticalLines(false);
		if (label.equals("Copy")) {
			table.setFont(new Font("Tahoma", Font.PLAIN, 24));
			table.setRowHeight(36);
		}

		int h = table.getModel().getRowCount() * table.getRowHeight();

		JScrollPane scrollPane = new JScrollPane(table);
		scrollPane.setPreferredSize(new Dimension(275, h));
		scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);

		add(scrollPane);
		add(buttonAndListModel);

		addClickListener();

		allButtons.add(buttonAndListModel);
	}

	public void createH(String label, NamedList listing, ArrayList<AbstractButtonPlusModel> allButtons) {
		buttonAndListModel = new ButtonAndListModel(label);

		setAlignmentY(Component.TOP_ALIGNMENT);
		setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

		buttonAndListModel.setAlignmentY(Component.TOP_ALIGNMENT);
		buttonAndListModel.listing = listing;

		// buttonAndListModel.listing.type = NamedList.TYPE.TEXT;

		GrfxOrder currOrder = grfxOrder;

		table = new JTable();
		table.setAlignmentX(Component.TOP_ALIGNMENT);
		if (currOrder != null) {
			table.setModel(listing.toTableModel(currOrder.getAssignedUsers()));
		} else {
			table.setModel(listing.toTableModel(null));
		}
		table.setTableHeader(null);
		table.getSelectionModel().addListSelectionListener(new MyListSelectionListener());
		table.getModel().addTableModelListener(new TableEditListener());
		table.setFillsViewportHeight(true);
		table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
		table.setShowGrid(false);
		table.setShowHorizontalLines(false);
		table.setShowVerticalLines(false);
		table.setRowHeight(36);

		int h = table.getModel().getRowCount() * table.getRowHeight();

		JScrollPane scrollPane = new JScrollPane(table);
		scrollPane.setPreferredSize(new Dimension(275, h));
		scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);

		add(scrollPane);
		add(buttonAndListModel);

		if (allButtons != null) {
			allButtons.add(buttonAndListModel);
		}
	}

	public void createchckbxSecret() {
		chckbxSecret = new JCheckBox();
		add(chckbxSecret);
	}

	public void addClickListener() {
		if (buttonAndListModel != null && buttonAndListModel.listing != null && buttonAndListModel.listing.type != null) {
			switch (buttonAndListModel.listing.type) {
				case NOTE:
					// buttonAndListModel.addActionListener(buttonAndListModel.new AddNoteActionListener());
					break;
				case FILENAME:
				case TEXT:
					buttonAndListModel.addActionListener(buttonAndListModel.new CopyToClipboardActionListener(buttonAndListModel.selectedValues));
					break;
				case STILLS:
				case FOOTAGE:
					buttonAndListModel.addActionListener(buttonAndListModel.new OpenFolderActionListener());
					break;
			}
		}
		// if (buttonAndListModel.listing.isText()) {
		// buttonAndListModel.addActionListener(buttonAndListModel.new
		// CopyToClipboardActionListener(buttonAndListModel.selectedValues));
		// } else {
		// buttonAndListModel.addActionListener(buttonAndListModel.new
		// OpenFolderActionListener());
		// }
	}

	public void makeDragAndDrop(DROP drop) {
		this.drop = drop;
		setTransferHandler(new FSTransfer());
	}

	public String getUNCpath(File f) {
		String filePath = f.getAbsolutePath();
		try {
			Runtime runTime = Runtime.getRuntime();
			Process process;
			process = runTime.exec("net use");
			InputStream inStream = process.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inStream);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String line = null;
			String[] components = null;
			while (null != (line = bufferedReader.readLine())) {
				components = line.split("\\s+");
				if ((components.length > 2) && (components[1].equals(filePath.substring(0, 2)))) {
					filePath = filePath.replace(components[1], components[2]);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filePath;
	}

	public void setTitleBorder(String str) {
		setBorder(new TitledBorder(new EtchedBorder(), str));
	}

	public class MyListSelectionListener implements ListSelectionListener {
		@Override
		public void valueChanged(ListSelectionEvent e) {
			ArrayList tableSelection = new ArrayList();

			if (table.getColumnSelectionAllowed() && !table.getRowSelectionAllowed()) {
				// Column selection is enabled
				// Get the indices of the selected columns
				int[] vColIndices = table.getSelectedColumns();
			} else if (!table.getColumnSelectionAllowed()
					&& table.getRowSelectionAllowed()) {
				// Row selection is enabled
				// Get the indices of the selected rows

				int[] rowIndices = table.getSelectedRows();

				for (int i = 0; i < rowIndices.length; i++) {
					tableSelection.add(table.getModel().getValueAt(rowIndices[i], 0));
				}

			} else if (table.getCellSelectionEnabled()) {
				// Individual cell selection is enabled

				// In SINGLE_SELECTION mode, the selected cell can be retrieved
				// using
				table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
				int rowIndex = table.getSelectedRow();
				int colIndex = table.getSelectedColumn();

				// In the other modes, the set of selected cells can be
				// retrieved using
				table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
				table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

				// Get the min and max ranges of selected cells
				int rowIndexStart = table.getSelectedRow();
				int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
				int colIndexStart = table.getSelectedColumn();
				int colIndexEnd = table.getColumnModel().getSelectionModel().getMaxSelectionIndex();

				// Check each cell in the range
				for (int r = rowIndexStart; r <= rowIndexEnd; r++) {
					for (int c = colIndexStart; c <= colIndexEnd; c++) {
						if (table.isCellSelected(r, c)) {
							tableSelection.add(table.getModel().getValueAt(r, c));
						}
					}
				}
			}
			buttonAndListModel.selectedValues = tableSelection.toArray();
		}
	}

	public class TableEditListener implements TableModelListener {

		@Override
		public void tableChanged(TableModelEvent e) {
			//Trace.info(e);
			GrfxItem currItem = buttonAndListModel.grfxItem;
			int row = e.getFirstRow();
			int column = e.getColumn();
			String columnName = ((DefaultTableModel) e.getSource()).getColumnName(column);
			String data = (String) ((DefaultTableModel) e.getSource()).getValueAt(row, column);
			//Trace.info("stop");

			String oldData = (String) buttonAndListModel.listing.get(row);
			String newData = data;

			buttonAndListModel.listing.set(row, data);
			GrfxOrder a = buttonAndListModel.grfxOrder;
			//Trace.info(e.getSource());
			buttonAndListModel.grfxItem.updateSQLItem();
			//GRFXOrdersMain.serverSocket.sendToClients(GfxProtocol.COMMAND.REFRESH, buttonAndListModel.grfxOrder.getIdOrder() + "");
			switch (buttonAndListModel.listing.type) {
				case TEXT:
					Notify.textEdited(buttonAndListModel.grfxOrder, Users.currentUser, oldData, newData);
					break;
				case STILLS:
					Notify.photosChanged(buttonAndListModel.grfxOrder, Users.currentUser, oldData, newData);
					break;
				case FOOTAGE:
					Notify.footageChanged(buttonAndListModel.grfxOrder, Users.currentUser, oldData, newData);
					break;
			}
		}

	}

	public class FSTransfer extends TransferHandler {
		public boolean importData(TransferHandler.TransferSupport support) {
			String UNCfilePath = "";
			//Trace.info(support);
			Transferable t = support.getTransferable();
			DataFlavor[] df = support.getDataFlavors();

			List data;
			try {
				data = (List) t.getTransferData(DataFlavor.javaFileListFlavor);

				Iterator i = data.iterator();
				while (i.hasNext()) {
					File f = (File) i.next();

					UNCfilePath = getUNCpath(f);
					//Trace.info(UNCfilePath);
				}
			} catch (UnsupportedFlavorException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			switch (drop) {
				case STILLS:
					buttonAndListModel.setStillFolder(UNCfilePath, buttonAndListModel.listing.id);
					OrderTree2.setBackgroundIfReady(ButtonListPanel.this, buttonAndListModel.grfxItem.getPhotoEditState());
					setTitleBorder("STILLS------" + UNCfilePath);
					// model.grfxOrder.setApprPhotoEdit(true); // need to poll
					// ALL the items and I don't feel like coding that right now
					break;
				case FOOTAGE:
					buttonAndListModel.setFootageFolder(UNCfilePath, buttonAndListModel.listing.id);
					OrderTree2.setBackgroundIfReady(ButtonListPanel.this, buttonAndListModel.grfxItem.getFootageState());
					setTitleBorder("FOOTAGE------" + UNCfilePath);
					// model.grfxOrder.setApprPhotoEdit(true); // need to poll
					// ALL the items and I don't feel like coding that right now
					break;
			}

			//Trace.info(UNCfilePath + " " + buttonAndListModel.listing.id);
			//GRFXOrdersMain.serverSocket.sendToClients(GfxProtocol.COMMAND.REFRESH, buttonAndListModel.grfxOrder.getIdOrder() + "");

			return true;
		}

		public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
			if (comp instanceof ButtonListPanel) {
				for (int i = 0; i < transferFlavors.length; i++) {
					if (!transferFlavors[i].equals(DataFlavor.javaFileListFlavor)) {
						return false;
					}
				}
				return true;
			}
			return false;
		}
	}
	*/
}
